﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS.Data.Repositorios;
using App.UI.Auxiliares;
using CMS.Data.Classes;
namespace App.UI
{
    public partial class CadastroUsuarios : System.Web.UI.Page
    {
        Metodos metodos = new Metodos();

        UsuarioRepository usuarioRepository = new UsuarioRepository();
        NivelPermissaoRepository nivelPermissoaRepository = new NivelPermissaoRepository();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LimparCampos();
                CarregarDropDownList();
                if (!String.IsNullOrEmpty(Request.QueryString["UsuarioId"]))
                    CarregarPagina();
                
            }
        }

        private void CarregarDropDownList()
        {
            List<NivelPermissao> lstNivelPermissao = nivelPermissoaRepository.SelectAll().ToList();

            ddlPermissao.DataSource = lstNivelPermissao;
            ddlPermissao.DataBind();

            ddlPermissao.Items.Insert(0, new ListItem("Selecione um tipo de Permissão", "0"));
        }

        private void CarregarPagina()
        {
            int Id = Request.QueryString["UsuarioId"].ToInt();

            Usuario usuario = usuarioRepository.SelectById(Id);

            if (usuario != null)
            {
                txtNome.Text = usuario.Nome;
                txtEmail.Text = usuario.Email;
                txtTipoCargo.Text = usuario.Cargo;
                ddlPermissao.SelectedValue = usuario.NivelPermissao_ID.ToString();
            }
        }

        #region Save Method's
       
        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            try
            {

                Usuario obj = Salvar();
                if (obj != null)
                {
                    if (!String.IsNullOrEmpty(Request.QueryString["UsuarioId"]))
                    {
                        ScriptManager.RegisterClientScriptBlock(this, GetType(), "notify", "SuccessUpdate();", true);
                    }
                    else
                    {
                        LimparCampos();
                        ScriptManager.RegisterClientScriptBlock(this, GetType(), "notify", "Success();", true);
                    }
                }
            }
            catch
            {
                ScriptManager.RegisterClientScriptBlock(this, GetType(), "notify", "Failed();", true);
            }
        }

        private Usuario Salvar()
        {
            if (metodos.ValidarLogin() == null)
                Response.Redirect("Login.aspx");

            Usuario obj = new Usuario();

            if (!String.IsNullOrEmpty(Request.QueryString["UsuarioId"]))
            {
                int Id = Request.QueryString["UsuarioId"].ToInt();

                if (Id > 0)
                    obj = usuarioRepository.SelectById(Id);
            }
            else
            {
                Usuario usu = usuarioRepository.SelectByEmail(txtEmail.Text);
                if (usu != null)
                {
                    ScriptManager.RegisterClientScriptBlock(this, GetType(), "alert", "alert('Este e-mail já existe em nossa base.')", true);
                    return null;
                }
            }

            

            obj.Nome = txtNome.Text;
            obj.Senha = txtPass.Text;
            obj.Cargo = txtTipoCargo.Text;
            obj.Email = txtEmail.Text;
            obj.Ativo = cbAtivo.Checked;
            obj.NivelPermissao_ID = ddlPermissao.SelectedValue.ToInt();

            usuarioRepository.Save(obj);

            

            return obj;

        }
      
        #endregion

        #region PageHelp Method's
        
        private void LimparCampos()
        {
            txtNome.Text = "";
            txtEmail.Text = "";
            txtTipoCargo.Text = "";
            txtPass.Text= "";
        }


        protected void cvSenha_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (txtPass.Text.Length < 6)
            {
                txtPass.Focus();

                args.IsValid = false;
                return;
            }
            else
                args.IsValid = true;
        }

        #endregion


    }
}